package com.mach.platform.service.js;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;

public class JsService {

    private static JsService me;
    private final ScriptEngine curScriptEngine;

    public static JsService get(){
        if(me == null){
            me = new JsService();
        }
        return me;
    }

    public static final String NASHORN_JS_ENGINE = "nashorn";
    public final static ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

    private JsService(){

        ScriptEngine eng = scriptEngineManager.getEngineByName(NASHORN_JS_ENGINE);
        this.curScriptEngine = eng;
        //Invocable inv = (Invocable)eng;

    }

    public Object exeJs(String js) throws ScriptException {
        return this.curScriptEngine.eval(js);
    }

    public ScriptEngine newNashornEng(){
        return scriptEngineManager.getEngineByName(NASHORN_JS_ENGINE);
    }

    public ScriptEngine newEng(String name){
        return scriptEngineManager.getEngineByName(name);
    }

//    public static void main(String[] args) throws ScriptException {
//        JsService.get().curScriptEngine.put("mm",(Map<Object,Object>)new HashMap<Object,Object>());
//        JsService.get().exeJs("var a__焊装UE1_05_有功电度_ =1");
//    }
}
